package com.xinghen.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinghen.security.core.SecurityResult;
import com.xinghen.security.core.properties.LoginResponseType;
import com.xinghen.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xinghen
 * @ClassName: DefaultAuthenticationFailureHandler
 * @Package: com.xinghen.security.core.authentication
 * @Description 默认的浏览器端认证失败处理器
 * @create 2018-04-18 11:49
 */
@Slf4j
public class DefaultAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private SecurityProperties securityProperties;

    public DefaultAuthenticationFailureHandler(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException, ServletException {
        log.info("登录失败");
        if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(new ObjectMapper()
                    .writeValueAsString(SecurityResult.error(HttpStatus.UNAUTHORIZED.value(), e.getMessage())));
        } else {
            super.onAuthenticationFailure(request, response, e);
        }
    }
}
